package com.shchekoldin.juliet.packager.plugins;

import com.shchekoldin.juliet.packager.utils.FilesIterator;
import com.shchekoldin.juliet.packager.utils.FilesIteratorEvent;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LocalFileOptimizer implements PackagerPlugin {

    private static final Pattern PRIVATE_MEMBER_PATTERN = Pattern.compile("\\b_[A-Za-z\\d]\\w*", Pattern.DOTALL);

    private static final String OPTIMIZE_PRIVATE_MEMBERS_KEY = "// #juliet-packager-optimize-private-members";

    // -------------------------------------------------------
    // -                        LOGIC                        -
    // -------------------------------------------------------

    private void subscribeOnFilesIteratorEvents(final FilesIterator filesIterator) {
        filesIterator.getOnIterate().add(new FilesIteratorEvent() {
            @Override
            public void run() {
                filesIterator.setCurrentFileContent(
                    optimizePrivateMembers(filesIterator.getCurrentFileContent())
                );
            }
        });
    }

    private String optimizePrivateMembers(String fileContent) {
        if (!fileContent.contains(OPTIMIZE_PRIVATE_MEMBERS_KEY)) {
            return fileContent;
        }

        Matcher matcher = PRIVATE_MEMBER_PATTERN.matcher(fileContent);
        Map<String, Boolean> membersNamesHash = new HashMap<String, Boolean>();

        while (matcher.find()) {
            membersNamesHash.put(matcher.group(), true);
        }

        int counter = 0;

        for (String memberName : membersNamesHash.keySet()) {
            fileContent = fileContent.replaceAll(memberName, "_" + String.valueOf(counter++));
        }

        return fileContent;
    }

    //
    // API
    //

    @Override
    public void initialize(FilesIterator filesIterator) {
        subscribeOnFilesIteratorEvents(filesIterator);
    }

}
